<template>
  <div class="cart-box">
    <s-header :title="'购物车'"></s-header>
    <van-loading class="loading-bg" size="48px" vertical v-show="lodingShow">加载中...</van-loading>
    <div class="cart-body">
      <van-checkbox-group class="checkbox-group" v-model='result' ref="checkboxGroup" @change="groupChange">
        <van-swipe-cell id="swipe-cell" :right-width="65" v-for="(item,index) in list" :key="index">
          <van-cell-group>
            <div class="good-item">
              <van-checkbox :name="item.goods_id" checked-color="#1cacac" />
              <div class="good-img">
                <img :src="item.image" />
              </div>
              <div class="good-desc">
                <div class="good-title">
                  <span>{{item.goods_name}}</span>
                  <span>x{{item.goods_count}}</span>
                </div>
                <div class="good-btn">
                  <div class="price">¥{{item.price}}</div>
                  <!-- 步进器 修改商品数量-->
                  <van-stepper integer :min="1" :max="item.count" v-model="item.goods_count" :name="item.goods_id" async-change
                    @change="onChange(item.goods_count,item.goods_id,item.count)" @overlimit="overlimit" />
                </div>
              </div>
            </div>
            <view slot="right" @click="onClose(item.goods_id)" class="van-swipe-cell__right">删除</view>
          </van-cell-group>
        </van-swipe-cell>
      </van-checkbox-group>
    </div>
    <van-submit-bar v-if="list.length > 0" class="submit-all" :price="total*100" button-text="结算" @submit="onSubmit" v-show="!lodingShow">
      <van-checkbox @click="allCheck" v-model="checkAll" checked-color="#1cacac">全选</van-checkbox>
    </van-submit-bar>
    <!-- 如果没有数据展示空页面 -->
    <div class="empty" v-if="!list.length">
      <van-icon name="smile-o" />
      <div class="title">购物车空空空如也</div>
      <van-button color="#1cacac" type="primary" block @click="goHome">前往首页</van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import sHeader from '@/components/SimpleHeader'
import { Toast, Dialog } from 'vant'
import { reactive, onMounted, computed, ref, Ref } from 'vue'
import { useRouter } from 'vue-router'
import { getCartData,updateGoodsCount,delGoodsByIds } from "@/service/cart";
// 初始化路由
const router = useRouter()
// 定义购物车数据类型
interface CartData {
	goods_id: string;
	count: number;
	goods_count: number;
	price: number;
	goods_name: string;
	image: string;
}
//是否全选 
let checkAll: Ref<boolean> = ref(false)
let result = ref<string[]>([])
//商品购物车列表数据
const list= ref<CartData[]> ([])
let lodingShow = ref(true)


// 计算属性  计算总价
let total = computed(() => {
  let sum = 0;
  let _list = list.value.filter((item) =>
    result.value.includes(item.goods_id)
  );
  _list.forEach((item) => {
    sum += item.goods_count * item.price;
  });
  return sum;
})

// 初始化
async function init() {
  const { data } = await getCartData();    
  data.forEach((item:CartData,index:number) =>{
    list.value[index]={
      goods_id:item.goods_id,
      image: item.image,
      goods_name:item.goods_name,
      count:item.count,
      price:item.price,
      goods_count:item.goods_count
    }
  })
  list.value = data
  // 相当于去重操作
  result.value=list.value.map((item) => item.goods_id)
  lodingShow.value = false
}
onMounted(() => {
  init()
})

// 修改商品数量
//value:购物车商品的数量
// name:商品id
// count:仓库中商品的总数
async function onChange(value: number, id: string,count: number) {
  const params = {
    goods_id: id,
    num:value
  }
    await updateGoodsCount(params)
    Toast.loading({ message: '修改中...', forbidClick: true });
    return new Promise((resolve) => {
      setTimeout(() => {
        Toast.clear();
        // 在 resolve 函数中返回 true 或 false
        resolve(true);
      }, 200);
    });
};

// 商品购买数量限制
function overlimit(value:any){
  if (value==="minus") {
    Toast.fail('该商品不能再减少了！')
  }else{
    Toast.fail('超过商品库存！')
  }
}

// 点击结算跳转至生成订单页面
async function onSubmit() {
  if (result.value.length > 0) {
    //得到已选择的商品数组 
    const params = []
    for(let item of result.value){
      for(let listitem of list.value){
        if(item==listitem.goods_id){params.push(listitem)}
      }
    }
    localStorage.setItem("cartItemIds",JSON.stringify(params))
    router.push(`create-order?cartItemIds=${JSON.stringify(params)}`)
  }else{
    Toast.fail('请选择商品进行结算！')
  }
}
// 删除商品
async function onClose(deletId:string) {
  const  goods_ids:string[]=[deletId]
  const params = {goods_ids}
  Dialog.confirm({
    message: '确定删除吗？',
    theme: 'round-button',
  }).then(() => {//确认删除    
     delGoodsByIds(JSON.stringify(params))
     init()  
  }).catch(() => {
  });
}

// 勾选商品
function groupChange(res: any) {  
  if (res.length == list.value.length) {
    checkAll.value = true;
  } else {
    checkAll.value = false;
  }
  result.value = res
}
// 全选事件
const allCheck = () => {
  if (checkAll.value) {
    result.value = list.value.map((item) => item.goods_id)
  } else {
    result.value = []
  }
}

// 没有数据 跳转到首页
function goHome(){
  router.push({ path: `home?` })
}

</script>

<style lang="less" scoped>
@import '../common/style/mixin.less';

.cart-box {
  .cart-body {
    margin: 60px 0 100px 0;
    padding-bottom: 120px;
    font-size: 12px;

    .good-item {
      display: flex;

      .good-img {
        img {
          .wh(100px, 100px);
        }
      }

      .good-desc {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        flex: 1;
        padding: 20px;

        .good-title {
          display: flex;
          justify-content: space-between;
        }

        .good-btn {
          display: flex;
          justify-content: space-between;

          .price {
            font-size: 16px;
            color: red;
            line-height: 28px;
          }

          .van-icon-delete {
            font-size: 20px;
            margin-top: 4px;
          }
        }
      }
    }

    .delete-button {
      width: 50px;
      height: 100%;
    }
  }

  .submit-all {
    margin-bottom: 47px;

    .van-checkbox {
      margin-left: 10px;
    }

    .van-submit-bar__text {
      margin-right: 10px;
    }

     .van-submit-bar__button {
      background-color:@primary;
    }


  }

  .van-swipe-cell__right {
    display: flex;
    width: 65px;
    height: 100%;
    font-size: 15px;
    line-height: 100%;
    color: #fff;
    align-items: center;
    justify-content: center;
    background-color: #f44;
  }

  .empty {
    width: 50%;
    margin: 0 auto;
    text-align: center;
    margin-top: -100px;
    .van-icon-smile-o {
      font-size: 50px;
    }

    .title {
      font-size: 16px;
      margin-bottom: 20px;
    }
  }

  .loading-bg{
    height: 100%;
    margin-top: 70%;
  }
}
</style>